package com.example.token.filter;

import com.example.token.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
//@Component
public class MyFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.setCharacterEncoding("UTF-8");
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.contains("login")) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        String token = httpServletRequest.getHeader("token");
        if (token == null) {
            log.error("请求头没有token");
            httpServletResponse.getWriter().write("未登录");
            return;
        }
        if (!jwtUtil.validateToken(token)) {
            log.error("无效token,登录过期");
            httpServletResponse.getWriter().write("登录过期，请重新登录");
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}